import { reactive } from "vue";
import { vToast } from "@/plugins/vToast";

// 初始商品数据
const initialState = reactive([
  {
    id: 1,
    name: "iPhone 13",
    category: "手机",
    price: 5999,
    image: "/images/iphone.png",
    createTime: 1718825600000,
    order: 1,
    status: 1, // 1 上架，0 下架
    stock: 100
  },
  {
    id: 2,
    name: "MacBook Pro",
    category: "笔记本电脑",
    price: 12999,
    image: "/images/macbook.png",
    createTime: 1717916800000,
    order: 2,
    status: 1,
    stock: 50
  },
  // 更多商品...
]);

// 分类数据（用于商品分类选择）
export const categories = [
  "手机",
  "笔记本电脑",
  "平板电脑",
  "智能手表",
  "耳机",
  "相机",
  "游戏主机",
  "显示器"
];

// 获取商品（带分页）
export const getGoods = (page, pageSize) => {
  const start = (page - 1) * pageSize;
  const end = start + pageSize;
  const data = initialState.slice(start, end);
  return {
    data,
    total: initialState.length
  };
};

// 添加商品
export const addGood = (newGood) => {
  const id = initialState.length > 0 ? Math.max(...initialState.map(g => g.id)) + 1 : 1;
  initialState.unshift({
    ...newGood,
    id,
    createTime: new Date().getTime()
  });
  vToast({ message: "商品已添加" });
  return true;
};

export const getGoodById = (id) => {
  // 从服务器或本地数据获取商品
  return new Promise((resolve) => {
    // 模拟API延迟
    setTimeout(() => {
      const good = initialState.find(g => g.id === id);
      resolve(good ? {...good} : null);
    }, 500);
  });
};

// 更新商品
export const updateGood = (updatedGood) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const index = initialState.findIndex(g => g.id === updatedGood.id);
      if (index !== -1) {
        initialState[index] = {...updatedGood};
        resolve(true);
      }
      resolve(false);
    }, 800);
  });
};
// 删除商品
export const deleteGood = (id) => {
  const index = initialState.findIndex(g => g.id === id);
  if (index !== -1) {
    initialState.splice(index, 1);
    vToast({ message: "商品已删除" });
    return true;
  }
  return false;
};

// 切换商品状态
export const toggleGoodStatus = (id) => {
  const good = initialState.find(g => g.id === id);
  if (good) {
    good.status = good.status ? 0 : 1;
    vToast({ 
      message: good.status ? "商品已上架" : "商品已下架", 
      position: "top"
    });
    return true;
  }
  return false;
};